package city.spring.configure;

import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;

/**
 * MyBatis配置
 *
 * @author HouKunLin
 * @date 2019/9/27 0027 23:43
 */
@Configuration
@EnableTransactionManagement
public class CustomMyBatisPlusConfiguration {
    private final static Logger logger = LoggerFactory.getLogger(CustomMyBatisPlusConfiguration.class);

    /**
     * 乐观锁配置
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    /**
     * SQL 执行分析拦截器 stopProceed 发现全表执行 delete update 是否停止运行
     */
    @Bean
    public SqlExplainInterceptor sqlExplainInterceptor() {
        return new SqlExplainInterceptor();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 配置 Sequence主键，使 MySQL 支持 Sequence主键（需要在数据库中增加sequence表和nextval函数来完成自增操作）
     */
    @Bean
    public IKeyGenerator iKeyGenerator() {
        return new IKeyGenerator() {
            @Override
            public String executeSql(String incrementerName) {
                return "CALL nextval('" + incrementerName + "')";
            }
        };
    }

    @PostConstruct
    public void postConstruct() {
        logger.debug("自定义MyBatisPlus配置: {}", this);
    }
}
